const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(_formatNumber).join('/') + ' ' + [hour, minute, second].map(_formatNumber).join(':')
}

const _formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

let urls = "111";
const ajax = (obj) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: urls+ obj.url,
      data: obj.data,
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: obj.type,
      success: function (res) {
        resolve(res)
        wx.hideLoading()
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(err)
      }
    })
  })

}

// 判断是否需要登录
function loginCheck(pageObj) {
  if (pageObj.onLoad) {
    let _onLoad = pageObj.onLoad;
    // 使用onLoad的话需要传递options
    pageObj.onLoad = function (options) {
      if (wx.getStorageSync('userInfo')) {
        // 获取当前页面
        let currentInstance = getPageInstance();
      
        _onLoad.call(currentInstance, options);

      }else{
        //跳转到登录页
        wx.redirectTo({
          url: "/pages/getuserinfo/getuserinfo"
          // url: "/pages/login/login"
        });
      }
    }
  }
  return pageObj;
}

// 获取当前页面
function getPageInstance() {
  var pages = getCurrentPages();
  return pages[pages.length - 1];
}



module.exports = {
  formatTime: formatTime,
  ajax,
  loginCheck,
  getApi,
  urls
}
